package com.example.test02;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.documentfile.provider.DocumentFile;

import java.io.IOException;

public class ResultActivity extends AppCompatActivity {
    private ImageView mediaThumbnail;
    private Button btnPlay;
    private Uri mediaUri;
    private boolean isVideo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);

        // 初始化 Toolbar
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar); // 将 Toolbar 设置为 ActionBar

        // 设置返回按钮点击事件
        toolbar.setNavigationOnClickListener(v -> {
            // 返回上一个页面
            onBackPressed();
        });

        // 初始化视图
        mediaThumbnail = findViewById(R.id.media_thumbnail);
        btnPlay = findViewById(R.id.btn_play);
        TextView resultText = findViewById(R.id.result_text);
        TextView dateText = findViewById(R.id.result_date);
        ImageView resultIcon = findViewById(R.id.result_icon); // 获取图标视图

        // 获取传递的数据
        String message = getIntent().getStringExtra("message_content");
        String mediaUriString = getIntent().getStringExtra("media_uri");
        String sendDate = getIntent().getStringExtra("send_date");

        if (mediaUriString == null) {
            Toast.makeText(this, "未找到媒体文件", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        mediaUri = Uri.parse(mediaUriString);

        // 检查 URI 权限并尝试恢复
        try {
            getContentResolver().takePersistableUriPermission(
                    mediaUri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION
            );
        } catch (SecurityException e) {
            e.printStackTrace();
            Toast.makeText(this, "无权限访问文件", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 检查文件是否存在
        DocumentFile documentFile = DocumentFile.fromSingleUri(this, mediaUri);
        if (documentFile == null || !documentFile.exists()) {
            Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 设置消息内容和日期
        resultText.setText(message);
        dateText.setText(sendDate);

        // 根据 message 设置图标
        if (message != null && message.contains("未")) {
            resultIcon.setImageResource(R.drawable.result_true); // 包含“未”字时设置图标为 result_true.png
        } else {
            resultIcon.setImageResource(R.drawable.result_fake); // 否则设置图标为 result_fake.png
        }

        // 判断媒体类型并加载预览
        String mimeType = getContentResolver().getType(mediaUri);
        if (mimeType != null) {
            if (mimeType.startsWith("video/")) {
                try {
                    loadVideoThumbnail();
                } catch (IOException e) {
                    e.printStackTrace();
                    mediaThumbnail.setImageResource(R.drawable.video_error_placeholder);
                }
                isVideo = true;
            } else if (mimeType.startsWith("audio/")) {
                mediaThumbnail.setImageResource(R.drawable.ic_audio_placeholder);
                isVideo = false;
            }
        }

        // 播放按钮逻辑
        btnPlay.setVisibility(View.VISIBLE);
        btnPlay.setOnClickListener(v -> {
            if (isVideo) {
                playVideo();
            } else {
                playAudio();
            }
        });
    }

    // 加载视频封面（第一帧）
    private void loadVideoThumbnail() throws IOException {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(this, mediaUri);
            Bitmap frame = retriever.getFrameAtTime();
            mediaThumbnail.setImageBitmap(frame);
        } catch (Exception e) {
            mediaThumbnail.setImageResource(R.drawable.video_error_placeholder);
        } finally {
            retriever.release();
        }
    }

    // 播放视频
    private void playVideo() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(mediaUri, "video/*");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(intent);
    }

    // 播放音频
    private void playAudio() {
        MediaPlayer mediaPlayer = MediaPlayer.create(this, mediaUri);
        if (mediaPlayer != null) {
            mediaPlayer.start();
            mediaPlayer.setOnCompletionListener(mp -> mp.release());
        } else {
            Toast.makeText(this, "无法播放音频文件", Toast.LENGTH_SHORT).show();
        }
    }
}